import {Component, OnInit, ViewChild, NgZone, Input} from '@angular/core';
import 'datatables';
import {Validators, FormBuilder, FormGroup} from "@angular/forms";
import {ModalDirective} from "ng2-bootstrap/ng2-bootstrap";
import {CertificateReissueInfo} from "./certificate-reissue-info.class";
import {CertificateReissueService} from "./certificate-reissue.service";
import {DataTablesComponent, DataTablesComponentConfig} from "app/theme/components/dataTables";

@Component({
  selector: 'certificate-reissue',
  templateUrl: 'certificate-reissue.component.html',
  styleUrls: ['certificate-reissue.component.scss'],
  providers: [CertificateReissueService]
})
export class CertificateReissueComponent implements OnInit {
  @Input() applyUrl;
  @Input() applyTableUrl;
  @Input() fileUploadUrl;
  @Input() applyInfoUrl;
  @Input() apprInfoUrl;

  @ViewChild('applyModal') applyModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private searchForm: CertReissueSearchForm = new CertReissueSearchForm();
  private applyForm: FormGroup;

  private apprDeleteUrl = '/water/certificate/delete';

  private disableUpload: boolean = false;
  private reissueProofPic: string = 'reissueProofPic';
  private sizeLimit = 2097152;

  private disableApplyBtn = true;
  private disableReviewBtn = true;
  private disableDeleteBtn = true;

  private selectedRowData: any = new CertificateReissueInfo();
  private applyDetailData: any = new CertificateReissueInfo();
  private applyInfo: any = new CertificateReissueInfo();

  private _errorMsg: string;
  private errorShow = false;

  private applyModalDisplay = true;

  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  public loading = false;

  constructor(private _fb: FormBuilder, private _service: CertificateReissueService) {
  }

  ngOnInit() {
    this.buildForm();
    this.initDatatables();
  }

  buildForm(): void {
    this.applyForm = this._fb.group(
      {
        'type': [''],
        'file1': [''],
      }
    );

    this.applyForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  private initDatatables() {
    this.dataTablesConfig.ajaxUrl = this.applyTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '证书类型', 'id': 'type'},
      {'name': '证书编号', 'id': 'serialno'},
      {'name': '姓名', 'id': 'name'},
      {'name': '身份证', 'id': 'idcard'},
      {'name': '公司名', 'id': 'companyname'},
      {'name': '签发日期', 'id': 'issuedate'},
      {'name': '有效期', 'id': 'availabletime'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable': true},
      {'name': '状态', 'id': 'verified'}
    ];
  }


  private onSubmit(): void {
    let ids = this.selectedRowData[0].ids;
    this.loading = true;
    this._service.submit(this.applyUrl, {ids: ids,reissueProofPic:this.applyInfo.reissueProofPic})
      .then(res => {
        if (res.status === "success") {
          this.apprApplyClose();
          this.dataTable.draw();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
        this.loading = false;
      }, error => {
        this._errorMsg = error;
      });
  }

  onValueChanged(data?: any) {
    // if (!this.applyForm) { return; }
    // const form = this.applyForm;
    // for (const field in this.formErrors) {

    //   this.formErrors[field] = '';
    //   const control = form.get(field);

    //   if (control && control.dirty && !control.valid) {
    //     const messages = this.validationMessages[field];
    //     for (const key in control.errors) {
    //       this.formErrors[field] += messages[key] + ' ';
    //     }
    //   }
    // }
  }

  review() {
    let data = this.verifyStatus();
    this.loadInfo(data.id, data.url, this.selectedRowData[0].verified, this.apprReviewModal);
  }

  verifyStatus() {
    let id;
    let url;
    if (this.selectedRowData[0].verified === '可申请') {
      id = this.selectedRowData[0].ids;
      url = this.applyInfoUrl;
    } else {
      id = this.selectedRowData[0].pkid;
      url = this.apprInfoUrl;
    }

    return {id: id, url: url};
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private loadInfo(id: string, url: string, status: string, apprModal: ModalDirective) {
    this.applyDetailData = new CertificateReissueInfo();
    this._service.reviewAppr(url, id, status)
      .then(res => {
        if (res.status === 'success') {
          this.applyDetailData = res.data;
          apprModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }


  private addApply(): void {
    this.applyModalDisplay = true;
    let data = this.verifyStatus();
    this.loadInfo(data.id, data.url, this.selectedRowData[0].verified, this.applyModal);
  }

  search() {
    this.dataTable.draw();
  }

  onFileUploading() {
    this.disableUpload = true;
  }

  onFinishUploading(replyObj: any) {
    this.applyInfo[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  onHideModal(): void {
    this.applyModalDisplay = false;
    jQuery(".modal-backdrop").remove();
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disableDeleteBtn = true;
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    this.disableReviewBtn = rowData.length !== 1;
    if (rowData.length === 1 && rowData[0].verified === '可申请') {
      this.disableApplyBtn = false;
      this.selectedRowData = rowData[0];
    } else {
      this.disableApplyBtn = true;
    }
    this.disableDeleteBtn = !(rowData[0].verified === '未通过');
    this.selectedRowData = rowData;
  }

  showDeleteModal() {
    this.apprDeleteModal.show();
  }

  public delete(): void {
    let pkids = [];
    for (let row of this.selectedRowData) {
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
          this.disableDeleteBtn = true;
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  public apprApplyClose(){
    this._errorMsg = null;
    this.applyModalDisplay = false;
    this.applyModal.hide()
  }

  public apprDeleteClose() {
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }
}

export class CertReissueSearchForm {
  public idcard: string = '';
  public name: string = '';
  public type: string = '';
  public verified: string = '可申请';
  public enddate: string = '';
  public startdate: string = '';
}
